package com.nuanshui.framework.utils;

import java.text.NumberFormat;
import java.util.Currency;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.collections4.map.LRUMap;

public final class CommonUtils {

	protected static final Map<String, NumberFormat> FORMAT_CACHE = new LRUMap<String, NumberFormat>(
			20, 100);

	@SuppressWarnings("unchecked")
	public static <K, V> Map<K, V> asMap(Object... kvs) {
		if (kvs.length % 2 != 0)
			throw new IllegalArgumentException("如参需要双数个");
		Map<K, V> ret = new HashMap<K, V>(kvs.length / 2);
		for (int i = 0; i < kvs.length; i += 2) {
			ret.put((K) kvs[i], (V) kvs[i + 1]);
		}
		return ret;
	}

	/**
	 * Provides a cached approach for creating NumberFormat instances. More
	 * performant than creating a new one each time.
	 * 
	 * @param locale
	 *            the Locale
	 * @param currency
	 *            the Currency
	 * @return either a new NumberFormat instance, or one taken from the cache
	 */
	public static NumberFormat getNumberFormatFromCache(Locale locale,
			Currency currency) {
		String key = locale.toString() + currency.getCurrencyCode();
		if (!FORMAT_CACHE.containsKey(key)) {
			NumberFormat format = NumberFormat.getCurrencyInstance(locale);
			format.setCurrency(currency);
			FORMAT_CACHE.put(key, format);
		}
		return FORMAT_CACHE.get(key);
	}

	public static Throwable getRootCause(Throwable t) {
		while (t.getCause() != null && t != t.getCause()) {
			t = t.getCause();
		}
		return t;
	}
}
